function jcb_export_spectra(filename,spectrum)
%%
if nargin<2
    spectrum='scattering';
end
if nargin<1 || isempty(filename)
    % get user to pick files
    [filelist,pathname] = jcb_pick_files('b*data.txt', ...
    'Please select files for which to export spectra',true,pwd);
else
    if strcmpi(filename,'all')
        filename='b';
    end
    [filelist,pathname] = jcb_select_files(filename,'spectra');
end
if isempty(filelist)
    return
end
%%
if strcmp(spectrum,'scattering')
    spectcol=2;
elseif strcmp(spectrum,'absorption')
    spectcol=3;
elseif strcmp(spectrum,'extinction')
    spectcol=4;
end

filelist=filelist(:);     % column cell-vector
n = size(filelist,1);
locstr = cell(n,1);
%%
for ii=1:n
    %% load file & extract data
    filename=strtrim(filelist{ii});
    disp(['extracting spectra from file ' filename]);
    data=load(fullfile(pathname,filename));
    if ii==1
        lambda=data(:,1);
        spectra = zeros(length(lambda),n);
    end
    
    spectra(:,ii) = data(:,spectcol);
        
    fileinfo=regexp(filename,'dose(?<btl>\d+)_(?<btw>\d+)_(?<gap>\d+)','names');
    mesh=regexp(filename,'m(?<mesh>\d+)','names');
    fileinfo.mesh=str2double(mesh.mesh);
    loc=regexp(filename,'loc(?<loc>\d+)sweep_d(?<d>\d+)','names');
    if isempty(loc)
        loc=regexp(filename,'loc(?<loc>\d+)','names');
    end
    switch str2double(loc.loc)
        case 1
            if length(fields(loc))>1
                locstr{ii}=[loc.d 'nm'];
            else
                locstr{ii}='10';
            end
        case 2
            locstr{ii}='20nm';
        case 3
            locstr{ii}='40nm';
        case 4
            locstr{ii}='108nm';
        case 5
            if length(fields(loc))>1
                locstr{ii}=['corner' loc.d];
            else
                locstr{ii}='corner';
            end
        case 6
            locstr{ii}='no Xtal';  % as no crystal used
    end    
end
%%
outfile=['dose' fileinfo.btl '_m' num2str(fileinfo.mesh) '_' ...
         spectrum '_spectra.txt'];
fid=fopen(outfile,'w');
fprintf(fid,['%% ' spectrum ' spectra for ' num2str(fileinfo.mesh/100) ...
             'nm mesh\n']);
headers='%% lambda';
format = '%8.4f';
for jj=1:n
    padsize=6-length(locstr{jj})/2;
    if padsize>0
        leftpad  = repmat(' ',1,floor(padsize));
        rightpad = repmat(' ',1, ceil(padsize));
    else
        leftpad='';
        rightpad='';
    end
    headers = [headers '\t' leftpad locstr{jj} rightpad];
    format = [format '\t%12.10f'];
end
fprintf(fid,[headers '\n']);
for ii=1:length(lambda)    
    fprintf(fid,[format '\n'],[lambda(ii) spectra(ii,:)]);
end
fclose(fid);
end